package com.fowo.api.syncAmazon.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.amazon.spapi.api.CatalogApi;
import com.amazon.spapi.api.ListingsApi;
import com.amazon.spapi.api.OrdersV0Api;
import com.amazon.spapi.api.ReportsApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.catalogitems.*;
import com.amazon.spapi.model.listingsitems.Item;
import com.amazon.spapi.model.reports.CreateReportSpecification;
import com.amazon.spapi.model.reports.Report;
import com.amazon.spapi.model.reports.ReportDocument;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.entity.ShopInfo;
import com.fowo.api.entity.TmpListing;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.TmpListingServiceImpl;
import com.fowo.api.syncAmazon.util.AmazonUtil;
import com.fowo.api.syncAmazon.util.GeneralUtil;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.service.FileService;
import com.squareup.okhttp.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;

@Slf4j
@Component
public class ListingService extends ReportService {
    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private AmazonUtil amazonUtil;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private TmpListingServiceImpl tmpListingService;
    @Resource
    private FileService fileService;

    private DatainterfaceAuthority entityAuthority;

    /**
     * 获取Listing
     * @throws Exception
     */
    public void getListing() throws Exception {
        entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Amazon")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
        for(ShopInfo shop : list){
            syncListingByShop(shop);
        }
    }

    /**
     * 获取店铺的Listing
     * @param shopInfo
     * @throws Exception
     */
    public void getListingByShop(ShopInfo shopInfo) throws Exception {
        entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
        syncListingByShop(shopInfo);
    }

    /**
     * 同步店铺Listing
     * @param shop
     * @throws Exception
     */
    public void syncListingByShop(ShopInfo shop) throws Exception {
        List<String> marketplaceIds = Arrays.asList(shop.getMarketplaceId().split(","));

        CreateReportSpecification body = new CreateReportSpecification();
        body.setReportType("GET_MERCHANT_LISTINGS_ALL_DATA");
        body.setMarketplaceIds(marketplaceIds);
        // 第一步 创建报告
        ReportsApi reportsApi = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
        final String reportId = createReport(reportsApi, body);
        // 第二步 检验报告是否完成
        ReportsApi reportsApi2 = amazonUtil.getReportsApi(entityAuthority,shop,2.0);
        final Report report = getReport(reportsApi2, reportId);
        // 第三步 获取报告连接
        ReportsApi reportsApi3 = amazonUtil.getReportsApi(entityAuthority,shop,0.0167);
        final ReportDocument reportDocument = reportsApi3.getReportDocument(report.getReportDocumentId());
        // 第四步 下载报告
        String compressionAlgorithm = null;
        if(null != reportDocument.getCompressionAlgorithm()){
            compressionAlgorithm = reportDocument.getCompressionAlgorithm().getValue();
        }
        download(reportDocument.getUrl(),compressionAlgorithm,shop);
    }

    /**
     * 下载报告
     * @param url
     * @param compressionAlgorithm
     * @throws IOException
     * @throws IllegalArgumentException
     */
    public void download(String url, String compressionAlgorithm,ShopInfo shop) throws IOException, IllegalArgumentException {
        OkHttpClient httpclient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = httpclient.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println(
                    String.format("Call to download content was unsuccessful with response code: %d and message: %s",
                            response.code(), response.message()));
            return;
        }

        try (ResponseBody responseBody = response.body()) {
            MediaType mediaType = MediaType.parse(response.header("Content-Type"));
            Charset charset = mediaType.charset();
            if (charset == null) {
                throw new IllegalArgumentException(String.format(
                        "Could not parse character set from '%s'", mediaType.toString()));
            }

            Closeable closeThis = null;
            try {
                InputStream inputStream = responseBody.byteStream();
                closeThis = inputStream;

                if ("GZIP".equals(compressionAlgorithm)) {
                    inputStream = new GZIPInputStream(inputStream);
                    closeThis = inputStream;
                }

                // This example assumes that the download content has a charset in the content-type header, e.g.
                // text/plain; charset=UTF-8
                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                    closeThis = inputStreamReader;

                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    closeThis = reader;

                    int lineNumber = 0;
                    String line;
                    List<TmpListing> list = new ArrayList<TmpListing>();
                    Map<String, Integer> indexMap = new HashMap<String, Integer>();
                    Set<String> skuset = new HashSet<String>();
                    Boolean isJP = "JP".equals(shop.getRegion()); //是否是日本站点
                    while ((line = reader.readLine()) != null)  {
                        String[] info = line.split("\t");
                        String name = null;
                        String description = null;
                        String listingId = null;
                        String sku = null;
                        String price = null;
                        String quantity = "0";
                        String opendate = null;
                        Date openDate = null;
                        String imageUrl = null;
                        String itemIsMarketplace = null;
                        String productIdType = null;
                        String zshopShippingFee = null;
                        String itemNote = null;
                        String itemCondition = null;
                        String zshopCategory = null;
                        String zshopBrowsePath = null;
                        String zshopStorefrontFeature = null;
                        String asin = null;
                        String willShipInternationally = null;
                        String expeditedShipping = null;
                        String productId = null;
                        String bidForFeaturedPlacement = null;
                        String addDelete = null;
                        String pendingQuantity = null;
                        String fulfillmentChannel = null;
                        String merchantShippingGroup = null;
                        String status = null;
                        if (lineNumber == 0) {

                            for (int i = 0; i < info.length; i++) {
                                indexMap.put(info[i], i);
                            }
                        } else {
                            if (info.length < indexMap.size()) {
                                continue;
                            }
                            if(info.length>indexMap.size()) {
                                if (indexMap.containsKey("seller-sku")) {
                                    sku = info[indexMap.get("seller-sku")+1];
                                } else {
                                    continue;
                                }
                                if (indexMap.containsKey("item-name")) {
                                    name = info[indexMap.get("item-name")+1];
                                } else {
                                    name = "";
                                }
                                if (indexMap.containsKey("item-description")) {
                                    description = info[indexMap.get("item-description")+1];
                                } else {
                                    description = "";
                                }
                                if (indexMap.containsKey("listing-id")) {
                                    listingId = info[indexMap.get("listing-id")+1];
                                } else {
                                    listingId = "";
                                }
                                if (indexMap.containsKey("price")) {
                                    price = info[indexMap.get("price")+1];
                                } else {
                                    price = "0";
                                }
                                if (indexMap.containsKey("quantity")) {
                                    quantity = info[indexMap.get("quantity")+1];
                                } else {
                                    quantity = "0";
                                }
                                if (indexMap.containsKey("open-date")) {
                                    opendate = info[indexMap.get("open-date")+1];
                                } else {
                                    opendate = null;
                                }
                                if (indexMap.containsKey("image-url")) {
                                    imageUrl = info[indexMap.get("image-url")+1];
                                } else {
                                    imageUrl = "";
                                }
                                if (indexMap.containsKey("item-is-marketplace")) {
                                    itemIsMarketplace = info[indexMap.get("item-is-marketplace")+1];
                                } else {
                                    itemIsMarketplace = "";
                                }
                                if (indexMap.containsKey("product-id-type")) {
                                    productIdType = info[indexMap.get("product-id-type")+1];
                                } else {
                                    productIdType = "";
                                }
                                if (indexMap.containsKey("zshop-shipping-fee")) {
                                    zshopShippingFee = info[indexMap.get("zshop-shipping-fee")+1];
                                } else {
                                    zshopShippingFee = "";
                                }
                                if (indexMap.containsKey("item-note")) {
                                    itemNote = info[indexMap.get("item-note")+1];
                                } else {
                                    itemNote = "";
                                }
                                if (indexMap.containsKey("item-condition")) {
                                    itemCondition = info[indexMap.get("item-condition")+1];
                                } else {
                                    itemCondition = "";
                                }
                                if (indexMap.containsKey("zshop-category1")) {
                                    zshopCategory = info[indexMap.get("zshop-category1")+1];
                                } else {
                                    zshopCategory = "";
                                }
                                if (indexMap.containsKey("zshop-browse-path")) {
                                    zshopBrowsePath = info[indexMap.get("zshop-browse-path")+1];
                                } else {
                                    zshopBrowsePath = "";
                                }
                                if (indexMap.containsKey("zshop-storefront-feature")) {
                                    zshopStorefrontFeature = info[indexMap.get("zshop-storefront-feature")+1];
                                } else {
                                    zshopStorefrontFeature = "";
                                }
                                if (indexMap.containsKey("asin1")) {
                                    asin = info[indexMap.get("asin1")+1];
                                } else {
                                    asin = "";
                                }
                                if (indexMap.containsKey("will-ship-internationally")) {
                                    willShipInternationally = info[indexMap.get("will-ship-internationally")+1];
                                } else {
                                    willShipInternationally = "";
                                }
                                if (indexMap.containsKey("expedited-shipping")) {
                                    expeditedShipping = info[indexMap.get("expedited-shipping")+1];
                                } else {
                                    expeditedShipping = "";
                                }
                                if (indexMap.containsKey("product-id")) {
                                    productId = info[indexMap.get("product-id")+1];
                                } else {
                                    productId = "";
                                }
                                if (indexMap.containsKey("bid-for-featured-placement")) {
                                    bidForFeaturedPlacement = info[indexMap.get("bid-for-featured-placement")+1];
                                } else {
                                    bidForFeaturedPlacement = "";
                                }
                                if (indexMap.containsKey("add-delete")) {
                                    addDelete = info[indexMap.get("add-delete")+1];
                                } else {
                                    addDelete = "";
                                }
                                if (indexMap.containsKey("pending-quantity")) {
                                    pendingQuantity = info[indexMap.get("pending-quantity")+1];
                                } else {
                                    pendingQuantity = "";
                                }
                                if (indexMap.containsKey("fulfillment-channel")) {
                                    fulfillmentChannel = info[indexMap.get("fulfillment-channel")+1];
                                } else {
                                    fulfillmentChannel = "";
                                }
                                if (indexMap.containsKey("merchant-shipping-group")) {
                                    merchantShippingGroup = info[indexMap.get("merchant-shipping-group")+1];
                                } else {
                                    merchantShippingGroup = "";
                                }
                                if (indexMap.containsKey("status")) {
                                    status = info[indexMap.get("status")+1];
                                } else {
                                    status = "";
                                }
                            } else {
                                if (indexMap.containsKey("seller-sku")) {
                                    sku = info[indexMap.get("seller-sku")];
                                } else {
                                    continue;
                                }
                                if (indexMap.containsKey("item-name")) {
                                    name = info[indexMap.get("item-name")];
                                } else {
                                    name = "";
                                }
                                if (indexMap.containsKey("item-description")) {
                                    description = info[indexMap.get("item-description")];
                                } else {
                                    description = "";
                                }
                                if (indexMap.containsKey("listing-id")) {
                                    listingId = info[indexMap.get("listing-id")];
                                } else {
                                    listingId = "";
                                }
                                if (indexMap.containsKey("price")) {
                                    price = info[indexMap.get("price")];
                                } else {
                                    price = "0";
                                }
                                if (indexMap.containsKey("quantity")) {
                                    quantity = info[indexMap.get("quantity")];
                                } else {
                                    quantity = "0";
                                }
                                if (indexMap.containsKey("open-date")) {
                                    opendate = info[indexMap.get("open-date")];
                                } else {
                                    opendate = null;
                                }
                                if (indexMap.containsKey("image-url")) {
                                    imageUrl = info[indexMap.get("image-url")];
                                } else {
                                    imageUrl = "";
                                }
                                if (indexMap.containsKey("item-is-marketplace")) {
                                    itemIsMarketplace = info[indexMap.get("item-is-marketplace")];
                                } else {
                                    itemIsMarketplace = "";
                                }
                                if (indexMap.containsKey("product-id-type")) {
                                    productIdType = info[indexMap.get("product-id-type")];
                                } else {
                                    productIdType = "";
                                }
                                if (indexMap.containsKey("zshop-shipping-fee")) {
                                    zshopShippingFee = info[indexMap.get("zshop-shipping-fee")];
                                } else {
                                    zshopShippingFee = "";
                                }
                                if (indexMap.containsKey("item-note")) {
                                    itemNote = info[indexMap.get("item-note")];
                                } else {
                                    itemNote = "";
                                }
                                if (indexMap.containsKey("item-condition")) {
                                    itemCondition = info[indexMap.get("item-condition")];
                                } else {
                                    itemCondition = "";
                                }
                                if (indexMap.containsKey("zshop-category1")) {
                                    zshopCategory = info[indexMap.get("zshop-category1")];
                                } else {
                                    zshopCategory = "";
                                }
                                if (indexMap.containsKey("zshop-browse-path")) {
                                    zshopBrowsePath = info[indexMap.get("zshop-browse-path")];
                                } else {
                                    zshopBrowsePath = "";
                                }
                                if (indexMap.containsKey("zshop-storefront-feature")) {
                                    zshopStorefrontFeature = info[indexMap.get("zshop-storefront-feature")];
                                } else {
                                    zshopStorefrontFeature = "";
                                }
                                if (indexMap.containsKey("asin1")) {
                                    asin = info[indexMap.get("asin1")];
                                } else {
                                    asin = "";
                                }
                                if (indexMap.containsKey("will-ship-internationally")) {
                                    willShipInternationally = info[indexMap.get("will-ship-internationally")];
                                } else {
                                    willShipInternationally = "";
                                }
                                if (indexMap.containsKey("expedited-shipping")) {
                                    expeditedShipping = info[indexMap.get("expedited-shipping")];
                                } else {
                                    expeditedShipping = "";
                                }
                                if (indexMap.containsKey("product-id")) {
                                    productId = info[indexMap.get("product-id")];
                                } else {
                                    productId = "";
                                }
                                if (indexMap.containsKey("bid-for-featured-placement")) {
                                    bidForFeaturedPlacement = info[indexMap.get("bid-for-featured-placement")];
                                } else {
                                    bidForFeaturedPlacement = "";
                                }
                                if (indexMap.containsKey("add-delete")) {
                                    addDelete = info[indexMap.get("add-delete")];
                                } else {
                                    addDelete = "";
                                }
                                if (indexMap.containsKey("pending-quantity")) {
                                    pendingQuantity = info[indexMap.get("pending-quantity")];
                                } else {
                                    pendingQuantity = "";
                                }
                                if (indexMap.containsKey("fulfillment-channel")) {
                                    fulfillmentChannel = info[indexMap.get("fulfillment-channel")];
                                } else {
                                    fulfillmentChannel = "";
                                }
                                if (indexMap.containsKey("merchant-shipping-group")) {
                                    merchantShippingGroup = info[indexMap.get("merchant-shipping-group")];
                                } else {
                                    merchantShippingGroup = "";
                                }
                                if (indexMap.containsKey("status")) {
                                    status = info[indexMap.get("status")];
                                } else {
                                    status = "";
                                }
                            }
                            if(status.equals("Incomplete")){//不完整的跳过
                                continue;
                            }
                            TmpListing tmp = new TmpListing();
                            tmp.setCountry(shop.getCountry());
                            tmp.setCreateTime(new Date());
                            tmp.setSid(shop.getId());
                            tmp.setName(name);
                            tmp.setDescription(description);
                            tmp.setListingId(listingId);
                            tmp.setSellerSku(sku);
                            if (StrUtil.isNotEmpty(price)){
                                try {
                                    tmp.setPrice(new BigDecimal(price));
                                } catch (Exception e) {
                                    log.error("SKU:"+sku+"的价格("+price+")格式化错误！");
                                    continue;
                                }
                            }
                            tmp.setQuantity(StrUtil.isBlank(quantity)? 0 : Integer.valueOf(quantity));
                            if (StrUtil.isNotEmpty(opendate)) {
                                SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");// 2019-12-06 03:30:06 PST, 05/09/2018 09:58:06 MEST
                                if (isJP) {
                                    sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                    sdf1.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
                                }
                                try {
                                    if(opendate.length()>19){
                                        openDate = sdf1.parse(opendate.substring(0, 19));// 2019-12-06 03:30:06
                                    } else {
                                        System.out.println(opendate);
                                    }
                                } catch (ParseException e) {
                                    if(opendate.length()>19){
                                        openDate = GeneralUtil.getDatez(opendate.substring(0, 19));
                                    } else {
                                        System.out.println(opendate);
                                    }
                                }
                            }
                            if (openDate!=null) {
                                tmp.setOpenDate(openDate);
                            }
                            tmp.setImageUrl(imageUrl);
                            tmp.setItemIsMarketplace(itemIsMarketplace);
                            tmp.setProductIdType(productIdType);
                            if (StrUtil.isNotEmpty(zshopShippingFee)){
                                try {
                                    tmp.setZshopShippingFee(new BigDecimal(zshopShippingFee));
                                } catch (Exception e) {
                                    log.error("SKU:"+sku+"的运费("+zshopShippingFee+")格式化错误！");
                                    continue;
                                }
                            }
                            tmp.setItemNote(itemNote);
                            tmp.setItemCondition(itemCondition);
                            tmp.setZshopCategory(zshopCategory);
                            tmp.setZshopBrowsePath(zshopBrowsePath);
                            tmp.setZshopStorefrontFeature(zshopStorefrontFeature);
                            tmp.setAsin(asin);
                            tmp.setWillShipInternationally(willShipInternationally);
                            tmp.setExpeditedShipping(expeditedShipping);
                            tmp.setProductId(productId);
                            tmp.setBidForFeaturedPlacement(bidForFeaturedPlacement);
                            tmp.setAddDelete(addDelete);
                            tmp.setPendingQuantity(pendingQuantity);

                            tmp.setFulfillmentChannel(fulfillmentChannel.equals("AMAZON_NA")?"FBA":"FBM");
                            tmp.setMerchantShippingGroup(merchantShippingGroup);
                            switch (status){
                                case "Active":
                                    tmp.setStatus("1");
                                    break;
                                default:
                                    tmp.setStatus("0");
                                    break;
                            }
//                            tmp.setStatus(status);

                            if (sku == null || skuset.contains(sku.trim().toUpperCase())) {
                                continue;
                            }
                            skuset.add(sku.trim().toUpperCase());
                            list.add(tmp);
                        }
                        info=null;
                        lineNumber++;
                        // Process line by line.
                    }
                    // fnsku
                    setListingFnsku(list,shop);
                    // listing其他信息
                    getCatalogItems(list,shop);
                    tmpListingService.saveBatch(list);
                } else {
                    //Handle content with binary data/other media types here.
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("处理Listing数据异常",e);
            } finally {
                if (closeThis != null) {
                    closeThis.close();
                }
            }
        }
    }

    public void setListingFnsku(List<TmpListing> list,ShopInfo shop)  {
        ListingsApi listingsApi = amazonUtil.getListingsApi(entityAuthority,shop);
        for(TmpListing tmpListing : list){
            if(StrUtil.isBlank(tmpListing.getSellerSku())){
                continue;
            }
            try{

                List<String> marketplaceIds = new ArrayList<>();
                marketplaceIds.add(shop.getMarketplaceId());
                String issueLocale = null;
                List<String> includedData = null;
                Item response = listingsApi.getListingsItem(shop.getSellerId(), tmpListing.getSellerSku(), marketplaceIds, issueLocale, includedData);
                tmpListing.setFnsku(Optional.of(response.getSummaries()).map(s -> s.get(0)).map(s ->s.getFnSku()).orElse(null));
            }catch (ApiException e){
                log.error(tmpListing.getSellerSku()+" 获取FNSKU异常",e);
            }

        }
    }

    public void getCatalogItems(List<TmpListing> list,ShopInfo shop) {
        CatalogApi catalogApi = amazonUtil.getCatalogApi(entityAuthority,shop);
        for(TmpListing tmpListing : list){
            if(StrUtil.isBlank(tmpListing.getAsin())){
                continue;
            }
            try{

                List<String> marketplaceIds = new ArrayList<>();
                marketplaceIds.add(shop.getMarketplaceId());
                List<String> includedData = new ArrayList<>();
                includedData.add("attributes");
                includedData.add("dimensions");
                includedData.add("identifiers");
                includedData.add("images");
                includedData.add("productTypes");
                includedData.add("relationships");
                includedData.add("salesRanks");
                includedData.add("summaries");
                String locale = null;
                com.amazon.spapi.model.catalogitems.Item response = catalogApi.getCatalogItem(tmpListing.getAsin(), marketplaceIds, includedData, locale);
                catalogToListing(response,tmpListing,shop);
            }catch (ApiException e){
                log.error(tmpListing.getSellerSku() + " 获取商品列表信息异常",e);
            }

        }
    }


    public void catalogToListing(com.amazon.spapi.model.catalogitems.Item item,TmpListing tmpListing,ShopInfo shopInfo){
//        tmpListing.setSid(shopInfo.getId());
//        tmpListing.setAsin(item.getAsin());
        if(null != item.getImages()){
            final ItemImagesByMarketplace itemImagesByMarketplace = item.getImages().stream()
                    .filter(i -> i.getMarketplaceId().equals(shopInfo.getMarketplaceId()))
                    .findFirst()
                    .get();
            final ItemImage main = itemImagesByMarketplace.getImages().stream().filter(i -> i.getVariant().getValue().equals("MAIN")).findFirst().get();
            if(null != main){
                tmpListing.setImageUrl(main.getLink());
                List<SysFile> image = uploadImage(main.getLink());
                tmpListing.setImg(image);
            }
        }
        if(null != item.getRelationships()){
            final ItemRelationshipsByMarketplace itemRelationshipsByMarketplace = item.getRelationships().stream()
                    .filter(r -> r.getMarketplaceId().equals(shopInfo.getMarketplaceId()))
                    .findFirst()
                    .get();
            ItemRelationship variation =  itemRelationshipsByMarketplace.getRelationships().stream()
                    .filter(r -> r.getType().getValue().equals("VARIATION"))
                    .findFirst()
                    .orElse(null);
            if(null != variation){
                String parentAsin = variation.getParentAsins().stream().collect(Collectors.joining(","));
                tmpListing.setParentAsin(parentAsin);
            }
        }
        if(null != item.getProductTypes()){
            final String productType = item.getProductTypes().stream()
                    .filter(t -> t.getMarketplaceId().equals(shopInfo.getMarketplaceId()))
                    .findFirst()
                    .map(t -> t.getProductType())
                    .orElse(null);
            tmpListing.setProductType(productType);
        }
        if(null != item.getSummaries()){
            String amazonClassify = item.getSummaries().stream()
                    .filter(s -> s.getMarketplaceId().equals(shopInfo.getMarketplaceId()))
                    .findFirst()
                    .map(s -> s.getItemClassification().getValue())
                    .orElse(null);
            tmpListing.setAmazonClassify(amazonClassify);
        }
        if(null != item.getSalesRanks()){
            final ItemSalesRanksByMarketplace itemSalesRanksByMarketplace = item.getSalesRanks().stream()
                    .filter(r -> r.getMarketplaceId().equals(shopInfo.getMarketplaceId()))
                    .findFirst()
                    .get();

            if(CollectionUtil.isNotEmpty(itemSalesRanksByMarketplace.getDisplayGroupRanks())){
                tmpListing.setRanking(itemSalesRanksByMarketplace.getDisplayGroupRanks().get(0).getRank().toString());
            }
//            itemSalesRanksByMarketplace.getClassificationRanks();
        }

    }

    public List<SysFile> uploadImage(String picUrl) {
        List<SysFile> fileList = new ArrayList<>();
        if (picUrl != null && !picUrl.isEmpty()) {
            MultipartFile multipartFile = null;
            try {
                multipartFile = onlineAddressTransferFile(picUrl);
                if (multipartFile != null) {
                    SysFile file = fileService.upload(multipartFile, null);
                    fileList.add(file);
                }
            } catch (Exception e) {
                log.error("上传失败：" + picUrl, e);
            }
        }
        return fileList;
    }

    public MultipartFile onlineAddressTransferFile(String strUrl) throws IOException {
        InputStream stream = getInputStreamByUrl(strUrl);
        if (!ObjectUtils.isEmpty(stream)) {
            return new MockMultipartFile("网络图片", FileUtil.getName(strUrl), "image/jpeg", stream);
        } else {
            log.error("获取网络文件失败 > " + strUrl);
        }
        return null;
    }

    public InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(strUrl)) {
                URL url = new URL(strUrl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(20 * 1000);

                final ByteArrayOutputStream output = new ByteArrayOutputStream();
                InputStream inputStream = conn.getInputStream();
                IOUtils.copy(inputStream, output);
                return new ByteArrayInputStream(output.toByteArray());
            }
        } catch (FileNotFoundException e) {
            log.error("FileNotFoundException: " + strUrl);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("获取图片时失败，未知异常: " + strUrl, e);
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                log.error("获取图片时，连接失败: " + strUrl, e);
            }
        }
        return null;
    }
}
